import FileSearchScreen from '@renderer/components/FileSearchScreen' // 新增导入
import SelectModelPopup from '@renderer/components/Popups/SelectModelPopup'
import { isMac } from '@renderer/config/constant'
import { useDefaultAssistant } from '@renderer/hooks/useAssistant'
import { useSettings } from '@renderer/hooks/useSettings'
import i18n from '@renderer/i18n'
import { getDefaultModel } from '@renderer/services/AssistantService'
import { EVENT_NAMES, EventEmitter } from '@renderer/services/EventService'
import { uuid } from '@renderer/utils'
import { defaultLanguage } from '@shared/config/constant'
import { IpcChannel } from '@shared/IpcChannel'
import { Divider } from 'antd'
import dayjs from 'dayjs'
import { isEmpty } from 'lodash'
import React, { FC, useCallback, useEffect, useRef, useState } from 'react'
import { useHotkeys } from 'react-hotkeys-hook'
import { useTranslation } from 'react-i18next'
import styled from 'styled-components'

import ChatWindow from '../chat/ChatWindow'
import TranslateWindow from '../translate/TranslateWindow'
import ClipboardPreview from './components/ClipboardPreview'
import FeatureMenus from './components/FeatureMenus'
import Footer from './components/Footer'
import InputBar from './components/InputBar'

// 这里是 mini 窗口的主页面脚本 HomeWindow.tsx
// 负责整个 mini 窗口的布局、路由切换、输入处理、菜单调用等
// 但"问答检索知识库"的核心逻辑（如向量检索、RAG、知识库查询）通常不会直接写在这里
// 这里会通过 onSendMessage 事件将消息发送到 EventEmitter，后续由主进程或服务端处理

// 你可以在 EventService、后端 API、或主进程相关脚本中查找知识库检索和问答的具体实现
// 例如：@renderer/services/EventService、api/qa.ts、main process、或 server 端的 RAG 相关代码

const HomeWindow: FC = () => {
  // 修改路由类型，添加 'file-search'
  const [route, setRoute] = useState<'home' | 'chat' | 'translate' | 'summary' | 'explanation' | 'file-search'>('home')
  const [isFirstMessage, setIsFirstMessage] = useState(true)
  const [clipboardText, setClipboardText] = useState('')
  const [selectedText, setSelectedText] = useState('')
  const [text, setText] = useState('')
  const [lastClipboardText, setLastClipboardText] = useState<string | null>(null)
  const textChange = useState(() => {})[1]
  const { defaultAssistant, updateDefaultAssistant } = useDefaultAssistant()
  // 修改：不再使用全局默认模型，而是使用assistant特定的模型
  // 确保currentModel始终有值，防止undefined错误
  const [currentModel, setCurrentModel] = useState(
    defaultAssistant.model || defaultAssistant.defaultModel || getDefaultModel()
  )
  const { language, readClipboardAtStartup, windowStyle, theme } = useSettings()
  const { t } = useTranslation()
  const inputBarRef = useRef<HTMLDivElement>(null)
  // 导入 FeatureMenus 组件的 ref 类型
  interface FeatureMenusRef {
    resetSelectedIndex: () => void
    prevFeature: () => void
    nextFeature: () => void
    useFeature: () => void
  }
  const featureMenusRef = useRef<FeatureMenusRef>(null)

  const referenceText = selectedText || clipboardText || text

  const content = isFirstMessage ? (referenceText === text ? text : `${referenceText}\n\n${text}`).trim() : text.trim()

  const readClipboard = useCallback(async () => {
    if (!readClipboardAtStartup) return

    const text = await navigator.clipboard.readText().catch(() => null)
    if (text && text !== lastClipboardText) {
      setLastClipboardText(text)
      setClipboardText(text.trim())
    }
  }, [readClipboardAtStartup, lastClipboardText])

  const focusInput = () => {
    if (inputBarRef.current) {
      const input = inputBarRef.current.querySelector('input')
      if (input) {
        input.focus()
      }
    }
  }

  const onWindowShow = useCallback(async () => {
    featureMenusRef.current?.resetSelectedIndex()
    readClipboard().then()
    focusInput()
  }, [readClipboard])

  useEffect(() => {
    readClipboard()
  }, [readClipboard])

  useEffect(() => {
    i18n.changeLanguage(language || navigator.language || defaultLanguage)
  }, [language])

  const onCloseWindow = () => window.api.miniWindow.hide()

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    // 使用非直接输入法时（例如中文、日文输入法），存在输入法键入过程
    // 键入过程不应有任何响应
    // 例子，中文输入法候选词过程使用`Enter`直接上屏字母，日文输入法候选词过程使用`Enter`输入假名
    // 输入法可以`Esc`终止候选词过程
    // 这两个例子的`Enter`和`Esc`快捷助手都不应该响应
    if (e.key === 'Process') {
      return
    }

    switch (e.code) {
      case 'Enter':
      case 'NumpadEnter':
        {
          e.preventDefault()
          if (content) {
            if (route === 'home') {
              featureMenusRef.current?.useFeature()
            } else {
              // 目前文本框只在'chat'时可以继续输入，这里相当于 route === 'chat'
              setRoute('chat')
              onSendMessage().then()
              focusInput()
            }
          }
        }
        break
      case 'Backspace':
        {
          textChange(() => {
            if (text.length === 0) {
              clearClipboard()
            }
          })
        }
        break
      case 'ArrowUp':
        {
          if (route === 'home') {
            e.preventDefault()
            featureMenusRef.current?.prevFeature()
          }
        }
        break
      case 'ArrowDown':
        {
          if (route === 'home') {
            e.preventDefault()
            featureMenusRef.current?.nextFeature()
          }
        }
        break
      case 'Escape':
        {
          setText('')
          setRoute('home')
          route === 'home' && onCloseWindow()
        }
        break
    }
  }

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setText(e.target.value)
  }

  const onSendMessage = useCallback(
    async (prompt?: string) => {
      if (isEmpty(content)) {
        return
      }

      setTimeout(() => {
        const message = {
          id: uuid(),
          role: 'user',
          content: prompt ? `${prompt}\n\n${content}` : content,
          assistantId: defaultAssistant.id,
          topicId: defaultAssistant.topics[0].id || uuid(),
          createdAt: dayjs().format('YYYY-MM-DD HH:mm:ss'),
          type: 'text',
          status: 'success'
        }
        EventEmitter.emit(EVENT_NAMES.SEND_MESSAGE, message)
        setIsFirstMessage(false)
        setText('') // ✅ 清除输入框内容
      }, 0)
    },
    [content, defaultAssistant.id, defaultAssistant.topics]
  )

  const clearClipboard = () => {
    setClipboardText('')
    setSelectedText('')
    focusInput()
  }

  // 处理模型选择 - 修改为不使用全局默认模型
  const handleModelSelect = async () => {
    const selectedModel = await SelectModelPopup.show({
      model: currentModel,
      width: 260,
      maxHeight: 280,
      showPin: false
    })
    if (selectedModel) {
      // 更新当前组件状态中的模型
      setCurrentModel(selectedModel)

      // 更新assistant的模型，但不更新全局默认模型
      const updatedAssistant = {
        ...defaultAssistant,
        model: selectedModel
      }
      updateDefaultAssistant(updatedAssistant)
    }
  }

  // If the input is focused, the `Esc` callback will not be triggered here.
  useHotkeys('esc', () => {
    if (route === 'home') {
      onCloseWindow()
    } else {
      setRoute('home')
      setText('')
    }
  })

  useEffect(() => {
    window.electron.ipcRenderer.on(IpcChannel.ShowMiniWindow, onWindowShow)
    window.electron.ipcRenderer.on(IpcChannel.SelectionAction, (_, { action, selectedText }) => {
      selectedText && setSelectedText(selectedText)
      action && setRoute(action)
      action === 'chat' && onSendMessage()
    })

    return () => {
      window.electron.ipcRenderer.removeAllListeners(IpcChannel.ShowMiniWindow)
      window.electron.ipcRenderer.removeAllListeners(IpcChannel.SelectionAction)
    }
  }, [onWindowShow, onSendMessage, setRoute])

  // 当路由为home时，初始化isFirstMessage为true
  useEffect(() => {
    if (route === 'home') {
      setIsFirstMessage(true)
    }
  }, [route])

  const backgroundColor = () => {
    // ONLY MAC: when transparent style + light theme: use vibrancy effect
    // because the dark style under mac's vibrancy effect has not been implemented
    if (
      isMac &&
      windowStyle === 'transparent' &&
      theme === 'light' &&
      !window.matchMedia('(prefers-color-scheme: dark)').matches
    ) {
      return 'transparent'
    }

    return 'var(--color-background)'
  }

  if (['chat', 'summary', 'explanation'].includes(route)) {
    return (
      <Container style={{ backgroundColor: backgroundColor() }}>
        {route === 'chat' && (
          <>
            <InputBar
              text={text}
              model={currentModel}
              referenceText={referenceText}
              placeholder={t('miniwindow.input.placeholder.empty', { model: currentModel.name })}
              handleKeyDown={handleKeyDown}
              handleChange={handleChange}
              ref={inputBarRef}
              onModelSelect={handleModelSelect}
            />
            <Divider style={{ margin: '10px 0' }} />
          </>
        )}
        {['summary', 'explanation'].includes(route) && (
          <div style={{ marginTop: 10 }}>
            <ClipboardPreview referenceText={referenceText} clearClipboard={clearClipboard} t={t} />
          </div>
        )}
        <ChatWindow route={route} model={currentModel} />
        <Divider style={{ margin: '10px 0' }} />
        <Footer route={route} onExit={() => setRoute('home')} model={currentModel} />
      </Container>
    )
  }

  if (route === 'translate') {
    return (
      <Container style={{ backgroundColor: backgroundColor() }}>
        <TranslateWindow text={referenceText} />
        <Divider style={{ margin: '10px 0' }} />
        <Footer route={route} onExit={() => setRoute('home')} model={currentModel} />
      </Container>
    )
  }

  // 添加文件搜索路由的渲染逻辑
  // 在第238行附近，确保没有多余的"return"字符显示
  // 如果是在JSX中出现的文本，需要删除
  if (route === 'file-search') {
    return <FileSearchScreen onClose={() => setRoute('home')} />
  }

  return (
    <Container style={{ backgroundColor: backgroundColor() }}>
      <InputBar
        text={text}
        model={currentModel}
        referenceText={referenceText}
        placeholder={
          referenceText && route === 'home'
            ? t('miniwindow.input.placeholder.title')
            : t('miniwindow.input.placeholder.empty', { model: currentModel.name })
        }
        handleKeyDown={handleKeyDown}
        handleChange={handleChange}
        ref={inputBarRef}
        onModelSelect={handleModelSelect}
      />
      <Divider style={{ margin: '10px 0' }} />
      <ClipboardPreview referenceText={referenceText} clearClipboard={clearClipboard} t={t} />
      <Main>
        <FeatureMenus
          setRoute={setRoute}
          onSendMessage={onSendMessage}
          text={content}
          ref={featureMenusRef as React.RefObject<FeatureMenusRef>}
        />
      </Main>
      <Divider style={{ margin: '10px 0' }} />
      <Footer
        route={route}
        canUseBackspace={text.length > 0 || clipboardText.length == 0}
        clearClipboard={clearClipboard}
        onExit={() => {
          setRoute('home')
          setText('')
          onCloseWindow()
        }}
        model={currentModel}
      />
    </Container>
  )
}

const Container = styled.div`
  display: flex;
  flex: 1;
  height: 380px;
  width: 280px; /* 从320px调整为280px，更加紧凑美观 */
  flex-direction: column;
  -webkit-app-region: drag;
  padding: 8px 10px;
`

const Main = styled.main`
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: hidden;
`

export default HomeWindow
